package pro.spring.wesocketController;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;



@SuppressWarnings("deprecation")
public class MyMessageInbound extends MessageInbound {
		
	private final static Map<Integer,List<MyMessageInbound>> connections =  new HashMap<Integer,List<MyMessageInbound>>();

	public static void addjson(String name,Integer drid){
		for (MyMessageInbound connection : connections.get(drid)) {
            try {
                connection.getWsOutbound().writeTextMessage(CharBuffer.wrap(name));
            } catch (IOException ignore) {
                // Ignore
            }
        }
	}
	
	@Override
    protected void onOpen(WsOutbound outbound) {
//		connections.put(1, this);
//		String message = "webSocket open";
//        addjson(message);
    }

    @Override
    protected void onClose(int status) {
    	connections.remove(this);
//        String message = "webSocket close";
//        addjson(message);
    }

    @Override
    protected void onBinaryMessage(ByteBuffer message) throws IOException {
    	//在这里处理二进制数据
    }

    @Override
    protected void onTextMessage(CharBuffer message) throws IOException {
    	Integer drid = Integer.valueOf(message.toString()); 
    	if(connections.get(drid)!=null){
    		List<MyMessageInbound> li =connections.get(drid);
    		li.add(this);
    		connections.put(drid,li);
    	}else{
    		List<MyMessageInbound> li = new ArrayList<MyMessageInbound>();
    		li.add(this);
        	connections.put(drid,li);
    	}
        //broadcast(filteredMessage);
    }
}
